<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="company-box box-card">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <!-- 按钮 -->
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="editRoleDialog = true">新增角色</el-button>
            <!-- 表格 -->
            <el-table
              :data="roles"
              border
              style="width: 100%"
            >
              <el-table-column
                type="index"
                label="序号"
                width="150"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="180"
                sortable
              />
              <el-table-column
                prop="description"
                label="描述"
                sortable
              />
              <el-table-column
                prop="address"
                label="操作"
                width="250"
                align="center"
              >
                <template v-slot="scope">
                  <el-button size="mini" type="text" @click="onSetPermission(scope.row)">分配权限</el-button>
                  <el-button size="mini" type="text" @click="editRoles(scope.row)">修改</el-button>
                  <el-button size="mini" type="text" @click="onDelRoles(scope.row)">删除</el-button>
                </template></el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              :current-page="page.page"
              :page-size="page.pagesize"
              layout="total, prev, pager, next"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane class="companyDatil" label="公司信息" name="info">
            <!-- 公司信息 -->
            <el-form class="companyinfo" size="mini" label-width="80px">
              <el-form-item label="企业名称">
                <el-input v-model="info.name" :disabled="true" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="info.companyAddress" :disabled="true" />
              </el-form-item>
              <el-form-item label="公司电话">
                <el-input v-model="info.companyPhone" :disabled="true" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="info.mailbox" :disabled="true" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="info.remarks" :disabled="true" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <el-dialog
      :title="(form.id? '编辑' : '新增') + '角色'"
      :visible.sync="editRoleDialog"
      width="30%"
      @close="onDialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="form.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      :title="setPermissionTitle"
      :visible.sync="setPermissionDialog"
      width="50%"
      @close="onClose"
    >
      <el-tree
        v-if="setPermissionDialog"
        ref="setPermissionTree"
        :data="permissionList"
        show-checkbox
        :props="defaultProps"
        :default-checked-keys="defaultKeys"
        default-expand-all
        icon-class=" "
        node-key="id"
        check-strictly
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="setPermissionDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSetPermissionSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, delRole, getRoleById, updateRoleById, addRole, getCompanyById } from '@/api/company'
import { getPermissionList, setPermissionToRole } from '@/api/permission'
import { transListToTree } from '@/utils'
export default {
  name: 'Settings',
  data() {
    return {
      activeName: 'role',
      roles: [],
      page: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      editRoleDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      info: {},
      setPermissionDialog: false,
      setPermissionTitle: '',
      permissionList: [],
      defaultProps: {
        label: 'name'
      },
      defaultKeys: [],
      roleId: ''
    }
  },

  created() {
    this.loadRoleList()
    this.getCompanyInfo()
  },

  methods: {
    async loadRoleList() {
      const res = await getRoleList(this.page)
      this.roles = res.rows
      this.total = res.total
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.loadRoleList()
    },
    onDelRoles(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delRole(row.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.loadRoleList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async editRoles(row) {
      const res = await getRoleById(row.id)
      this.form = res
      this.editRoleDialog = true
    },
    async onSave() {
      try {
        await this.$refs.form.validate()
        if (this.form.id) {
          await updateRoleById(this.form)
        } else {
          await addRole(this.form)
        }
        this.$message.success('操作成功')
        this.loadRoleList()
        this.editRoleDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    onDialogClose() {
      this.$refs.form.resetFields()
      setTimeout(() => {
        this.form = {
          name: '',
          description: ''
        }
      }, 200)
    },
    async getCompanyInfo() {
      const res = await getCompanyById(this.$store.state.user.userInfo.companyId)
      this.info = res
    },
    async onSetPermission(row) {
      this.roleId = row.id
      this.setPermissionTitle = `为[${row.name}]分配权限`
      this.setPermissionDialog = true
      const res = await getRoleById(row.id)
      this.defaultKeys = res.permIds
      this.permissionList = transListToTree('0', await getPermissionList())
    },
    async onSetPermissionSave() {
      const permissionIds = this.$refs.setPermissionTree.getCheckedKeys()
      if (!permissionIds.length) return this.$message.error('请选择必要的权限')
      await setPermissionToRole({ id: this.roleId, permIds: permissionIds })
      this.$message.success('分配成功')
      this.setPermissionDialog = false
    },
    onClose() {
      this.setPermissionDialog = false
      this.defaultKeys = []
    }
  }
}
</script>

<style scoped lang='scss'>
 .company-box{
    ::v-deep.el-tabs__item{
     font-size: 18px;
     width: 150px;
     padding: 0 30px;
     text-align: center;
   }
   .el-table{
     margin: 10px 0;
   }
   .el-pagination{
     display: flex;
     justify-content: flex-end;
   }
   .companyDatil{
     display: flex;
     justify-content: center;
    .companyinfo{
      width: 50%;
    }
   }
 }
</style>
